package com.opus.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.opus.entity.Admin;
import com.opus.service.IAdminService;
import com.opus.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * 登录
 */
@Controller
@RequestMapping("/api/login")
public class LoginController {

    @Autowired
    private IAdminService iAdminService;

    /**
     * 登录
     *
     * @return
     */
    @RequestMapping("/author")
    @ResponseBody
    public Result author(HttpServletRequest request, HttpSession session) {
        String type = request.getParameter("type");
        String account = request.getParameter("account");
        String pwd = request.getParameter("pwd");
        Admin admin = this.iAdminService.login(account, pwd, type);
        if (admin == null) {
            return Result.reError("账户密码错误");
        }
        //保存登录数据
        session.setAttribute("admin", admin);
        return Result.reOk("登录成功");
    }

    /**
     * 注册
     *
     * @return
     */
    @RequestMapping("/register")
    @ResponseBody
    public Result register(HttpServletRequest request, HttpSession session) {
        String type = request.getParameter("type");
        String account = request.getParameter("account");
        String pwd = request.getParameter("pwd");
        String nickname = request.getParameter("nickname");
        QueryWrapper<Admin> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",account);
        queryWrapper.eq("type",type);
        Admin admin = this.iAdminService.getOne(queryWrapper);
        if (admin != null) {
            return Result.reError("账号已存在，请更换账号注册");
        }
        admin=new Admin();
        admin.setCtime(new Date());
        admin.setPwd(pwd);
        admin.setUsername(account);
        admin.setNickname(nickname);
        admin.setType(Integer.parseInt(type));
        this.iAdminService.save(admin);
        return Result.reOk("注册成功");
    }

    /**
     * 获取当前登录的用户信息
     *
     * @return
     */
    @RequestMapping("/getAccountInfo")
    @ResponseBody
    public Result getAccountInfo(HttpServletRequest request, HttpSession session) {
        Admin admin = (Admin) session.getAttribute("admin");
        if (admin == null) {
            admin.setCtime(new Date());
            return Result.reError("登录信息已过期");
        }
        return Result.reOk("查询成功", admin);
    }


}